import tkinter as tk
import redis
import os
from util import get_delete_data_from_redis
import tkinter.font as tkFont
import json
from PIL import Image, ImageTk
import requests
from setting import *
import logging
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class InventoryUi:

    # goods_list = [
    #     {'image_path': 'maofeng_1704177712061.jpg', 'tea_name': "蒙山毛峰", "number": "2", "price": 15},        
    #     {'image_path': 'maofeng_1704177712061.jpg', 'tea_name': "蒙山毛毛", "number": "3", "price": 1.1},

    # ]

    def __init__(self) -> None:

        self.is_show_goods = False # 渲染标识


        self.r = redis.Redis(host='localhost', port=6379, db=0)

        # 创建一个订阅者对象
        self.p = self.r.pubsub()

        # 订阅频道
        self.p.subscribe('door_status')

        self.root = tk.Tk()

        self.root.attributes('-fullscreen', True)

        self.ui_args = self.ui_args()

        # 字体初始化
        self.font_style_content = tkFont.Font(family="AR PL UKai CN", size=int(self.ui_args["goods_size"]))
        self.font_style_top = tkFont.Font(family="AR PL UMing CN", size=int(self.ui_args["title_size"]))
        self.font_style_bottom = tkFont.Font(family="AR PL UMing CN", size=int(self.ui_args["bottom_status_size"]))
        self.font_style_bottom_total = tkFont.Font(family="AR PL UMing CN", size=int(self.ui_args["bottom_total_size"]), weight="bold")

        # 背景颜色初始化
        self.top_color = self.ui_args["top_color"]
        self.mid_color = self.ui_args["mid_color"]

        self.layout() # 总体布局

        # 内容渲染
        self.top_content() # 顶部内容渲染

        self.bottom_content()  # 底部内容渲染

        self.update_data()

        self.root.mainloop() # 启动



    def ui_args(self):

        if os.path.exists("/home/linaro/.ui_args.json"):

            with open("/home/linaro/.ui_args.json", encoding="utf-8") as f:

                return json.loads(f.read())
            
        else:

            return {
                "top_color": "#2c5cb3",
                "mid_color": "#3399FF",
                "title_size": 28,
                "goods_size": 14,
                "bottom_status_size": 18,
                "bottom_total_size": 20,
                "goods_font_color": "black",
                "title_font_color": "white",
                "bottom_status_color": "white",
                "bottom_total_color": "white",
                "top_weight": "2",
                "mid_weight": "6",
                "bottom_weight": "2",
            }
        
    def layout(self):

        # 设置网格的行和列权重
        self.root.grid_rowconfigure(0, weight=int(self.ui_args["top_weight"]))
        self.root.grid_rowconfigure(1, weight=int(self.ui_args["mid_weight"]))
        self.root.grid_rowconfigure(2, weight=int(self.ui_args["bottom_weight"]))
        self.root.grid_columnconfigure(0, weight=1)

        # 创建三个Frame分别用于上中下部分
        self.frame_top = tk.Frame(self.root, bg=self.top_color)
        self.frame_top.grid(row=0, column=0, sticky="nsew")
        self.frame_top.pack_propagate(False)  # 禁止self.frame_top自动调整大小

        self.frame_center = tk.Frame(self.root, bg=self.mid_color)
        self.frame_center.grid(row=1, column=0, sticky="nsew")
        self.frame_center.pack_propagate(False)  # 禁止self.frame_center自动调整大小


        self.frame_bottom = tk.Frame(self.root, bg=self.top_color)
        self.frame_bottom.grid(row=2, column=0, sticky="nsew")
        self.frame_bottom.pack_propagate(False)  # 禁止frame_bottom自动调整大小 

    
    def top_content(self, title: str = "选购商品"): # 顶部内容
    
        self.label_product_top = tk.Label(self.frame_top, text=title, bg=self.top_color, fg=self.ui_args["title_font_color"], font=self.font_style_top)
        self.label_product_top.pack(expand=True, fill="both")

        self.frame_top.grid_rowconfigure(0, weight=1)
        self.frame_top.grid_columnconfigure(0, weight=1)

    
    def bottom_content(self): # 底部内容

        # 底部状态
        self.label_status = tk.Label(self.frame_bottom, text="设备状态：门锁打开", bg=self.top_color, fg=self.ui_args["bottom_status_color"], font=self.font_style_bottom)
        self.label_status.pack(side="left", expand=True, fill="x", padx=50)

        # 底部总计
        self.label_total = tk.Label(self.frame_bottom, text="共 0 件商品，￥0.00元", bg=self.top_color, fg=self.ui_args["bottom_total_color"], font=self.font_style_bottom_total)
        self.label_total.pack(side="left", expand=True, fill="x", padx=50)

        self.frame_bottom.grid_columnconfigure(0, weight=1)
        self.frame_bottom.grid_columnconfigure(1, weight=1)

    
    def center_content(self, goods_list): # 中间商品渲染

        '''goods_list = [{'image_path': 'maofeng_1704177712061.jpg', 'tea_name': "蒙山毛峰", "number": "2"}, ... ...]
        '''

        # if self.is_show_goods == True: # 已经渲染过了

        #     return

            
        # 清空frame_center中的子组件
        for child in self.frame_center.winfo_children():
            child.destroy()

        # 网格分割
        self.frame_center.grid_columnconfigure(0, weight=1)
        self.frame_center.grid_columnconfigure(1, weight=1)
        self.frame_center.grid_columnconfigure(2, weight=1)
        self.frame_center.grid_columnconfigure(3, weight=1)
        self.frame_center.grid_columnconfigure(4, weight=1)
        self.frame_center.grid_rowconfigure(0, weight=1)
        self.frame_center.grid_rowconfigure(1, weight=1)

        desired_width, desired_height = 80,80
        num_per_row = 5  # 每行展示的图片数量

        for i, image_info in enumerate(goods_list):
            row = i // num_per_row  # 计算所在行数
            column = i % num_per_row  # 计算所在列数

            frame_goods = tk.Frame(self.frame_center, bg=self.mid_color)
            frame_goods.grid(row=row, column=column, padx=10, pady=10)  # 设置间距

            # 加载图片
            image_path = image_info['image_path']

            try:
                image = Image.open(image_path)
                image = image.resize((desired_width, desired_height))


            except Exception as e:

                image = Image.new("RGB", (desired_width, desired_height), "white")

                os.remove(image_path)

            photo = ImageTk.PhotoImage(image)
            
            label_image = tk.Label(frame_goods, image=photo, bg=self.mid_color)
            label_image.pack(side="top")

            label_text1 = tk.Label(frame_goods, text=image_info['tea_name'], bg=self.mid_color, fg=self.ui_args["goods_font_color"], font=self.font_style_content)
            label_text1.pack(side="top")

            label_text2 = tk.Label(frame_goods, text="X " + str(image_info['number']), bg=self.mid_color, fg=self.ui_args["goods_font_color"], font=self.font_style_content)
            label_text2.pack(side="top")

            label_image.image = photo  # 需要保持对图片对象的引用，以防止被垃圾回收

        
        # self.is_show_goods == True # 设置为已经渲染

    def get_goods_info_api(self, tags_list =['e280f30200000000714d8941','e280f30200000000714d8ce9']):


        goods_list = [
            # {'image_path': 'maofeng_1704177712061.jpg', 'tea_name': "蒙山毛峰", "number": 2, "price": 15},        
            # {'image_path': 'maofeng_1704177712061.jpg', 'tea_name': "蒙山毛毛", "number": 3, "price": 1.1},

        ]

        # rfids = ",".join([f"'{x}'" for x in tags_list])

        params = {
            "rfids":str(tags_list).replace("[", '').replace("]", '').replace('"', "'").replace(" ", "")
        }

        print(params)

        r = requests.get(GOODS_INFO_API, params=params)

        if r.json()["result"] == None:

            return {"goods_list": [], "total_price": 0.0, "total_goods": 0 }

        print(r.json())

        # data: [b'e28068940000501083c3c0ff', b'e28068940000401083c3c142']
        # {'success': True, 'message': '获取成功!', 'code': 200, 'result': [{'id': '1744163669164859393', 'createBy': 'admin', 'createTime': '2024-01-08 09:06:38', 'updateBy': 'admin', 'updateTime': '2024-02-23 08:51:04', 'sysOrgCode': 'A01', 'cateid': '1590548229652185090', 'spec': '每箱20个', 'title': '大红袍', 'img': 'https://vending.nsenz.cn/vending/sys/common/static/temp/新享绿茶_1708649462991.jpg', 'qrcode': '112111', 'detail': '', 'brand': '', 'adviceprice': None, 'price': None, 'state': '2', 'numindevice': None, 'num': 2, 'applynum': None, 'auditnum': None, 'amount': None, 'vrfid': None, 'fillcnt': None, 'curcnt': None, 'rfidcnt': None, 'warehousecnt': None, 'isoutstock': None}], 'timestamp': 1709213357997}

        for item in r.json()["result"]:

            image_file = "/home/linaro/{}".format(os.path.basename(item["img"]))

            if not os.path.exists(image_file):

                with open(image_file, 'wb') as f:

                    try:

                        response = requests.get(item["img"])

                        f.write(response.content)

                    except Exception as e:

                        logger.error("下载图片错误：{}".format(str(e)))


            # 价格有时为空

            price = item["price"]

            if not price:

                price = 0.0

            else:

                price = float(item["price"])

            item_info = {
                'image_path': image_file, 
                'tea_name': item["title"], 
                "number": int(item["num"]), 
                "price": price
            } 

            goods_list.append(item_info)

        total_price = 0.0
        total_goods = 0

        for i in goods_list:

            total_price += i['number'] * i["price"]

            total_goods += i['number']

        return {"goods_list": goods_list, "total_price": total_price, "total_goods": total_goods }


    def update_data(self):
        # 更新数据源
        status = self.r.get(CABINET_CURRENT_STATUS)
        status = status.decode() if status else ""

        cabinet_current_order_status = self.r.get(CABINET_CURRENT_ORDER_STATUS)

        # 设备状态渲染
        self.label_status.config(text="设备状态：{}".format(status))

        if cabinet_current_order_status==None:
            cabinet_current_order_status = ""
        else:
            cabinet_current_order_status = cabinet_current_order_status.decode()

        print(cabinet_current_order_status)

        # 顶部内容更新
        if cabinet_current_order_status == "补货":

            self.label_product_top.config(text="正在补货")

        elif cabinet_current_order_status == "购物":

            self.label_product_top.config(text="正在选购")

        elif cabinet_current_order_status == "无任务":

            self.label_total.config(text="")
            self.label_product_top.config(text="欢迎选购")


        else:

            self.label_product_top.config(text="欢迎选购")
        
        if status == "盘点结束":

            print(f"------{status}")

            # 从数据源获取新数据（例如从Redis中获取数据）
            data = get_delete_data_from_redis()  # 替换为适当的数据源函数

            print("data: {}".format(data))

            if cabinet_current_order_status in ["补货", "购物"]:

                if self.is_show_goods == False:

                    goods_info = self.get_goods_info_api([item.decode('utf-8') for item in data])

                    total_price = goods_info.get("total_price")

                    total_goods = goods_info.get('total_goods')

                    print("---{}".format(cabinet_current_order_status))

                    self.center_content(goods_list=goods_info["goods_list"]) # 渲染商品

                    

                    # 文字内容渲染
                    if cabinet_current_order_status == "补货":

                        self.label_product_top.config(text="补货完成")

                        self.label_total.config(text="共 {}件商品".format(total_goods))


                    elif cabinet_current_order_status == "购物":

                        self.label_product_top.config(text="购物完成")

                        self.label_total.config(text="共 {}件商品，￥{}元".format(total_goods, total_price))

                    self.is_show_goods = True
                        
        else:

            print(f"^^^^^^^^^^{status}")

            self.center_content([])

            self.label_total.config(text="共 0 件商品，￥ 0元")

            self.is_show_goods = False



            # label_product.config(text = "--")
            # label_product_quantity.config(text = "--")

    
        self.root.after(1000, self.update_data)  # 每1秒钟更新一次


if __name__ == "__main__":

    InventoryUi()

